package com.M.follow;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;

import java.util.concurrent.TimeUnit;

/**
 * zk实现选举
 *
 * @author kanlei
 * @email freefree.me@qq.com
 * @since 2021/9/4
 */
@Slf4j
public class MFollow {
    private ZooKeeper zk;

    {
        try {
            zk = new ZooKeeper("localhost:2181", 3000, event -> {
                if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                    log.info("connect successfully");
                }
            });
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }

    public void lead() throws Exception {
        zk.create("/lead", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT,
                (rc, path, ctx, name) -> {
                    if (rc == KeeperException.Code.NODEEXISTS.intValue()) {
                        try {
                            zk.exists("/lead", event -> {
                                if (event.getType() == Watcher.Event.EventType.NodeDeleted) {
                                    try {
                                        lead();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        } catch (Exception e) {
                            log.info(e.getMessage());
                        }
                    } else if (rc == KeeperException.Code.OK.intValue()){
                        try {
                            log.info("{} as master.",Thread.currentThread().getName());
                            TimeUnit.SECONDS.sleep(1);
                            zk.delete("/lead", -1);
                            log.info("{} outline.",Thread.currentThread().getName());
                        } catch (Exception e) {
                            log.info(e.getMessage());
                        }
                    }
                }, "ctx");
    }
}
